package server

import (
	"encoding/json"
	"fmt"
	"net/http"
	"text/template"

	"github.com/go-programing-tour-book/chatroom/global"
	"github.com/go-programing-tour-book/chatroom/logic"
)

func httpHandleFunc(w http.ResponseWriter, r *http.Request) {
	//主要作用是解析一个或多个文件，并将这些文件中的模板定义加载到一个
	// *template.Template 对象中，后续可使用该对象执行模板渲染操作。
	tpl, err := template.ParseFiles(global.RootDir + "/template/home.html")
	if err != nil {
		fmt.Fprint(w, "模版解析错误", err)
		return
	}

	err = tpl.Execute(w, nil)
	if err != nil {
		fmt.Fprint(w, "模版执行错误")
		return
	}
}

func userListHandleFunc(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)

	userlist := logic.BroadCaster.GetUserList()
	b, err := json.Marshal(userlist)
	if err != nil {
		fmt.Fprint(w, `[]`)
	} else {
		fmt.Fprint(w, string(b))
	}
}
